<?php
/**
 * 分类管理
 */
class CategoryApp extends CommonApp{

	/**
	 *分类列表
	 */
	function indexAct(){
		//My::clear('category');//清除分类缓存
		$catId = My::arr2var($_GET,'cat_id');
		$title = I('get.title');
		if(!My::is_id($catId) AND My::arr2var($_GET,'item')!=''){
			$catId = M('category')->item2id(My::arr2var($_GET,'item'));
		}
		//排除$item=menu的分类（该分类统一移到index.php?app=cat&item=menu中管理）
		if(M('category')->id2item($catId)=='menu'){
			$this->ajaxReturn(404,"后台菜单管理请到Cat中<a href='".Router::encodeUrl("index.php?app=cat&item=menu")."'>请点击</a>");
		}
		//有父分类参数时,读取父分类标题
		if(My::is_id($catId))	$this->assign("title", My::id2field('category',$catId,'title'));//页面标题:取顶级分类名
		//标题搜索
		if($title!='') {
			//得到父分类下的所有子分类id的IN语句
			$IN = '';
			if(My::is_id($catId)){
				$IN = M('category')->id2submenu($catId,array('publish'=>'all'));
				$IN = My::arr2one($IN,'id');
				$IN = is_array($IN)?implode(',',$IN):"";
				$IN = !empty($IN)?"AND id IN({$IN})":"";
			}
			//查找
			$searchResult = DB('category')->where("`title` like '%{$title}%' $IN")->select();
			//得到包括相应搜索结果的所有对应父分类列表
			$result = M('category')->ids2eachParent(My::arr2one($searchResult,'id'));
		}
		//无搜索条件,只显示整个大类
		else{
			$result = M('category')->id2submenu($catId,array('level'=>My::arr2var($_GET,'level'),'hasParent'=>true,'publish'=>'all'));
		}
		//最大允许级别
		$max_level = M('category')->id2topParent($catId);
		$this->assign('max_level',isset($max_level['params']['level'])?$max_level['params']['level']:0);
		//父分类
		$parent = DB('category')->where("parent_id=0")->order("ordering ASC")->select();
		$this->assign('parent',$parent);
		//parent_id
		if(is_array($result))
			$this->assign('parent_id',key($result));
		
		$this->assign('level',array('0'=>'子分类级数','1'=>'1级','2'=>'2级','3'=>'3级'));//下拉框搜索
		$this->assign("result",$result);
		
		if(My::arr2var($_GET,'tpl')!='')
			$this->display('Category/'.My::arr2var($_GET,'tpl'));
		else
			$this->display();
	}

	//编辑
	function modifyAct(){
		$id = My::arr2var($_GET,'id');
		$result = array();
		//编辑
		if(My::is_id($id)){
			$result = My::id2detail('category',$id);
			if(!$result)
				$this->ajaxReturn(404,"数据不存在!!!＜id={$id}＞");
		}
		$this->assign("text",(My::is_id($id)?'编辑':'添加'));
		$this->assign("result",$result);
		//父分类名称
		$cat_id = My::is_id(My::arr2var($_GET,'parent_id'))?$_GET['parent_id']:((isset($result['parent_id']) AND My::is_id($result['parent_id']))?$result['parent_id']:0);
		$this->assign("cat_name",($cat_name=My::id2field('category',$cat_id,'title')));
		//页面标题,用于面包屑
		$title=M('category')->id2topParent($id);$this->assign('title',!empty($title['title'])?$title['title']:$cat_name);
		//父分类树
		$parent = M('category')->id2topParent($cat_id);
		$parent = M('category')->id2select($parent['id'],array('level'=>($parent['youLevel']-1)));
		$this->assign('parent',$parent['select']);
		//分类id->自定义表单
		$FORM = Form::catId2FORM($cat_id);//统一用顶级分类的表单配置属性
		$this->assign('FORM',$FORM);
		//echo "<pre>"; print_r($params);exit;
		if(My::arr2var($_GET,'tpl')!='')
			$this->display('Category/'.My::arr2var($_GET,'tpl'));
		else
			$this->display();
	}
	
	/**
	 * 保存 (添加/编辑)
	 */
	function saveAct(){
		//echo "<pre>";print_r($_POST);exit;
		//表单验证(分类id 或 表单模型唯一名称)
		if(My::is_id(My::arr2var($_POST,'id')) OR My::is_id(My::arr2var($_POST,'parent_id')))
			$this->verify(My::arr2var($_POST,'verifyId'));
		$id = $_POST['id'] = My::is_id(My::arr2var($_POST,'id'))?$_POST['id']:0;
		$item = My::arr2var($_POST,'item');
		if(My::is_id($id)){//编辑
			if(My::arr2var($_POST,'title')=='') $this->ajaxReturn(300,"标题不能为空");
			//防止item唯一名重复
			if(My::is_var($item)) {
				$has = DB('category')->where("`item`='{$item}' AND `id`<>{$id}")->count();
				if($has) $this->ajaxReturn(300,"唯一名称: {$item} 名称已经存在!");
			}
			$_POST['parent_id']=My::is_id(My::arr2var($_POST,'parent_id'))?$_POST['parent_id']:0;
			//插入
			$ok=DB('category')->where("`id`='{$id}'")->clear()->save($_POST);
			//返回
			if($ok) $this->ajaxReturn(200,"编辑成功!");
			else  $this->ajaxReturn(300,"编辑失败!");
		}else{//修改
			if(My::arr2var($_POST,'title')=='') $this->ajaxReturn(300,"标题不能为空");
			//防止item唯一名重复
			if(!empty($item)) {
				$has = DB('category')->where("`item`='{$item}' AND item<>''")->count();
				if($has) $this->ajaxReturn(300,"唯一名称: {$item} 名称已经存在!");
			}
			$_POST['adddate']=date("Y-m-d H:i:s");//添加时间
			$_POST['parent_id']=My::is_id(My::arr2var($_POST,'parent_id'))?$_POST['parent_id']:0;
			$ok=DB('category')->clear()->add($_POST);
			if($ok) $this->ajaxReturn(200,"添加成功!");
			else $this->ajaxReturn(300,"添加失败!");
		}
	}

	/**
	 * 删除子分类(禁止删除父分类)
	 */
	public function delete_categoryAct(){
		if(isset($_POST['check_id']) && is_array($_POST['check_id']) && count($_POST['check_id'])>0){
			$str="";
			foreach($_POST['check_id'] as $key=>$value){
				if(!My::is_id($value)) continue;
				$post_table = My::arr2var($_POST,'table');
				if(!My::is_table($post_table))
				    $this->ajaxReturn(300, "数据表不存在({$post_table})!");
				//读取当前数据
				$temp = DB($post_table)->where("`id`='{$value}'")->find();
				//不存在该数据
				if(!$temp){
					$str.="ID:{$value} 该数据不存在!<br>";
					continue;
				}
				$temp['params'] = My::decodeJson($temp['params']);
				//得到关联数据表(如当前分类没有关联数据表时,从顶级分类中找关联表)
				if(!empty($temp['params']['table'])){
					$table = $temp['params']['table'];
				}else{
					$parent = M('category')->id2topParent($temp['id']);
					$parent['params'] = My::decodeJson($parent['params']);
					$table = !empty($parent['params']['table'])?$parent['params']['table']:'';
				}
				//如存在关联表,检查关联的表中是否有数据,如有数据不给删除
				if(!empty($table) AND My::is_table($table)){
					if($num=DB($table)->where("cat_id='{$temp['id']}'")->count()>0){
						$str .= "ID:{$value} 该分类在表({$table})中有关联的({$num})条数据,删除失败!<br>";
						continue;
					}
				}
				//判断表单模型是否存在数据,,存在在不给删除
				if(!empty($temp['params']['verify_item']) OR !empty($temp['item'])){
					if(!empty($temp['params']['verify_item']))
						$id_=M('category')->item2id($temp['params']['verify_item']);
					else
						$id_=M('category')->item2id($temp['item']);
					if(My::is_id($id_)){
						if($num=DB('form')->where("`cat_id`='{$id_}'")->count()>0){
							$str.="ID:{$value} 在表表单模型中有关联的({$num})条数据,删除失败!!<br>";
							continue;
						}
					}
				}
				//
				if(DB($post_table)->where("id=$value AND hot=1")->count()>0)
					$str.="ID:{$value} 删除失败, 不能删除重要标识数据!<br>";
				elseif(DB($post_table)->where("`parent_id`={$value}")->count()==0){
					$ok=DB(I('request.table'))->where("id=$value AND hot<>1")->clear()->delete();//不删除带hot重要标识的数据
					$str.="ID:{$value} 删除成功!<br>";
				}else $str.="ID:{$value} 删除失败, 不能删除含有子分类的父分类!<br>";
			}
			$this->ajaxReturn(200, $str);
		}else{
			$this->ajaxReturn(300, '删除失败!');
		}
	}

}